package com.ecoolex.discount.sales.job.scheduler;

import com.ecoolex.discount.sales.core.manager.DiscountOrderManager;
import com.ecoolex.discount.sales.core.manager.DiscountProductGiftCardManager;
import com.ecoolex.discount.sales.core.manager.DiscountProductVouchersManager;
import com.ecoolex.discount.sales.entity.DiscountOrder;
import com.ecoolex.discount.sales.enums.DiscountProductDiscountMode;
import com.ecoolex.framework.common.util.Assert;
import com.ecoolex.framework.scheduler.Job;
import com.ecoolex.framework.scheduler.JobComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 折扣订单处理
 */
@JobComponent
public class DiscountOrderProcessJob {

    private Logger log = LoggerFactory.getLogger(DiscountOrderProcessJob.class);

    @Autowired
    private DiscountOrderManager discountOrderManager;
    @Autowired
    private DiscountProductGiftCardManager discountProductGiftCardManager;
    @Autowired
    private DiscountProductVouchersManager discountProductVouchersManager;

    @Job(name = "discount.sales.DiscountOrderProcessJob.processOrder", describe = "处理折扣订单(发卡/充值/礼品卡)")
    public void processOrder() {
        List<DiscountOrder> discountOrderList = discountOrderManager.queryPaidAndUnknownProcessStatus(10);
        discountOrderList.forEach(order -> {
            // 更新到中间态成功的话, 则继续进行处理动作
            if (discountOrderManager.updateToProcessingStatus(order, this.getClass().getSimpleName())) {
                try {
                    if (DiscountProductDiscountMode.GIFT_CARD.equal(order.getDiscountMode())) {
                        // 礼品卡
                        discountProductGiftCardManager.processOrder(order, this.getClass().getSimpleName());
                    } else if (DiscountProductDiscountMode.VOUCHERS.equal(order.getDiscountMode())) {
                        // 折扣券
                        discountProductVouchersManager.processOrder(order, this.getClass().getSimpleName());
                    } else {
                        Assert.throwVerifyException("不支持类型");
                    }
                    discountOrderManager.updateToProcessSucceedStatus(order, this.getClass().getSimpleName());
                } catch (Exception e) {
                    log.error("发卡异常", e);
                    discountOrderManager.updateToProcessFailedStatus(order, e.getMessage(), this.getClass().getSimpleName());
                }
            }
        });
    }
}
